package com.example.socialapp.ui.auth.forgotpassword

import androidx.lifecycle.viewModelScope
import com.example.socialapp.domain.usecase.auth.ForgotPasswordUseCase
import com.example.socialapp.ui.base.mvi.MviViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

/**
 * 忘记密码界面的ViewModel
 */
@HiltViewModel
class ForgotPasswordViewModel @Inject constructor(
    private val forgotPasswordUseCase: ForgotPasswordUseCase
) : MviViewModel<ForgotPasswordState, ForgotPasswordIntent, ForgotPasswordEffect>() {

    override fun createInitialState(): ForgotPasswordState = ForgotPasswordState()

    override fun processIntent(intent: ForgotPasswordIntent) {
        when (intent) {
            is ForgotPasswordIntent.UpdateEmail -> updateEmail(intent.email)
            is ForgotPasswordIntent.SubmitReset -> submitReset()
            is ForgotPasswordIntent.NavigateToLogin -> navigateToLogin()
        }
    }

    /**
     * 更新邮箱
     */
    private fun updateEmail(email: String) {
        updateState { it.copy(
            email = email,
            isEmailError = false,
            emailErrorMessage = ""
        ) }
    }

    /**
     * 提交重置密码请求
     */
    private fun submitReset() {
        val currentState = state.value
        val email = currentState.email

        // 设置加载状态
        updateState { it.copy(isLoading = true) }
        
        viewModelScope.launch {
            forgotPasswordUseCase(email)
                .onSuccess {
                    Timber.d("重置密码邮件发送成功: $email")
                    updateState {
                        it.copy(
                            isLoading = false,
                            isResetSent = true
                        )
                    }
                    emitEffect(ForgotPasswordEffect.ShowSuccess("重置密码邮件已发送，请查收"))
                }
                .onFailure { error ->
                    Timber.e(error, "重置密码失败")
                    
                    if (error.message?.contains("邮箱") == true) {
                        updateState {
                            it.copy(
                                isLoading = false,
                                isEmailError = true,
                                emailErrorMessage = error.message ?: "邮箱无效"
                            )
                        }
                    } else {
                        updateState { it.copy(isLoading = false) }
                        emitEffect(ForgotPasswordEffect.ShowError(error.message ?: "重置密码失败"))
                    }
                }
        }
    }

    /**
     * 导航到登录界面
     */
    private fun navigateToLogin() {
        emitEffect(ForgotPasswordEffect.NavigateToLogin)
    }
} 